/**
 * A stack of cards (3 cards).
 * This will be used to display the stack.
 */

package threecard.android.card;

import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

public class CardStack implements Comparable<CardStack> {
	/** The array of cards */
	private PlayingCard[] cardArray = new PlayingCard[3];

	/** */
	private Boolean flipable = true;

	public Boolean getFlipable() {
		return flipable;
	}

	public void setFlipable(Boolean flipable) {
		this.flipable = flipable;
	}

	/**
	 * 
	 * @param value1
	 *            value of the first card
	 * @param suit1
	 *            suit value of the first card.
	 * @param value2
	 *            value of the second card
	 * @param suit2
	 *            suit value of the first card.
	 * @param value3
	 *            value of the third card
	 * @param suit3
	 *            suit value of the third card.
	 * @throws Exception
	 *             TODO
	 */
	public CardStack(int value1, int suit1, int value2, int suit2, int value3,
			int suit3) throws Exception {
		setCard(0, value1, suit1);
		setCard(1, value2, suit2);
		setCard(2, value3, suit3);

	}

	public void setCard(int card_number, int value, int suit) throws Exception {
		if (card_number > 2 || card_number < 0) {
			throw new Exception("Invalid card number");
		}

		cardArray[card_number] = new PlayingCard(value, suit);
	}

	public int cardValue() {
		int sum = 0;
		for (int i = 0; i < 3; i++) {
			sum += cardArray[i].getValue();
		}

		return sum;
	}

	/**
	 * Compare two card stacks. This method will be implemented on the server
	 * side instead.
	 */
	@Override
	public int compareTo(CardStack another) {
		return 0;
	}

	/**
	 * TODO: add more option to format the images of the stack.
	 * 
	 * @param context
	 * @return
	 */
	public RelativeLayout drawStack(Context context) {
		RelativeLayout result = new RelativeLayout(context);
		CustomImageButton iv[];
		iv = new CustomImageButton[3];

		// Add three ImageView to this.
		for (int i = 0; i < 3; i++) {
			iv[i] = new CustomImageButton(context, cardArray[i].getValue(),
					cardArray[i].getSuit(), true);

			RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			lp.setMargins(30 * i, 0, 5 * (i + 1), 0);
			iv[i].setLayoutParams(lp);

			// Click to flip the image.
			iv[i].setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (flipable)
						((CustomImageButton) v).flip();
				}
			});

			// add this to the layout.
			result.addView(iv[i]);

		}
		return result;
	}
}
